import F from './../libs/fetch'
import URL from './../libs/Url'

import {
    CATEGORY_DISABLE,
    REQUEST_POSTS,
    RECEIVE_POSTS,
    REMOVED_CATEGOERY,
    REMOVE_REQUEST_CATEGOERY,
    OPEN_MODAL,
    CLOSE_MODAL,
    SELECT_SUBREDDIT,

    SELECT_ALL,
    SELECT_ITEM,

    INVALIDATE_SUBREDDIT,
} from './../actionsType/news'
/*
 * action 创建函数
 */
export function category_disable(text) {
    return {type: CATEGORY_DISABLE, ...text}
}

/**
 * flag : true | false
 * @param flag
 * @returns {{type: string, subreddit: *}}
 */
export function selectAll(flag) {
    return {
        type: SELECT_ALL,
        flag
    }
}

/***
 * combine action
 */
export function selectItem(index) {
    return dispatch=> {
        dispatch(category_disable({num: (index.checked ? 1 : -1)}));
        dispatch(select_(index))
    }
}
export function select_(index) {
    return {
        type: SELECT_ITEM,
        ...index
    }
}

export function selectSubreddit(keyword) {
    return {
        type: SELECT_SUBREDDIT,
        keyword
    }
}

export function invalidateSubreddit(keyword) {
    return {
        type: INVALIDATE_SUBREDDIT,
        keyword
    }
}

function request(keyword) {
    return {
        type: REQUEST_POSTS,
        keyword
    }
}

function receive(keyword, json) {
    return {
        type: RECEIVE_POSTS,
        keyword,
        data: json,
        receivedAt: Date.now()
    }
}


function fetchCategory_(keyword) {
    return dispatch => {
        dispatch(request(keyword))
        return F.fetch(URL.NEWS_FIND, {body: {keyword: keyword}})
            .then(json => {
                return dispatch(receive(keyword, json))
            })
    }
}

/**
 * remove category action
 */
function remove_request(categoryIds) {
    return {
        type: REMOVE_REQUEST_CATEGOERY,
        ...categoryIds,
    }
}
function removed(categoryIds) {
    return {
        type: REMOVED_CATEGOERY,
        ...categoryIds,
    }
}
export function removeCategory(categoryIds) {
    return dispatch => {
        dispatch(remove_request(categoryIds))
        return F.fetch(URL.CATEGORY_DELETE, {body: categoryIds})
            .then(json => {
                // dispatch(category_disable({num:}))
                return dispatch(removed(categoryIds, json))
            })
    }
}

export function openModal() {
    return {
        type: OPEN_MODAL,
    }
}
export function closeModal() {
    return {
        type: CLOSE_MODAL,
    }
}

function shouldFetchCategory(state, keyword) {
    const posts = state.categories.data.data.length;
    //1. length==0 2. length!=0 && newkyword!=oldkyword
    if (!posts || posts && keyword != state.categories.keyword) {
        return true
    } else {
        return false
    }
}

export function fetchCategory(keyword = '') {
    return (dispatch, getState) => {
        if (shouldFetchCategory(getState(), keyword)) {
            return dispatch(fetchCategory_(keyword))
        }
    }
}